﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace T03ChatServer
{
    class Broadcast
    {
        public static int SYSTEM_MSG = 1;
        public static int CLIENT_MSG = 2;
        /// <summary>
        /// 广播消息
        /// </summary>
        /// <param name="msg">消息内容</param>
        /// <param name="uName">消息发送者</param>
        /// <param name="clientList">消息接收者</param>
        /// <param name="flag">消息类型（1.系统消息2.用户消息）</param>
        public static void PushMessage(string msg, string uName, Dictionary<string,Socket> clientList, int flag) {
            foreach (var item in clientList) {
                Socket _socket = item.Value;
                string msgTemp = null;
                byte[] dataBytes = new byte[4096];
                if (1 == flag)
                {
                    //系统消息
                    msgTemp = "【系统消息】" + msg + "\t\t" + DateTime.Now;
                }
                else if(2 == flag){
                    msgTemp = uName + ":" + msg + "\t\t" + DateTime.Now;
                }
                dataBytes = Encoding.UTF8.GetBytes(msgTemp);
                try {
                    _socket.Send(dataBytes);
                }
                catch (Exception e) {
                    _socket.Close();
                    _socket = null;
                    Debug.WriteLine(e.ToString());
                    continue;
                }

            }

        }


    }
}
